import socketserver
# from robot_api import chat
from tencent_ai import chat
# from serverer.robot_api import chat
from mysqldb_server import add_one_message
# 服务器收到用户发送的消息后，判断对方是否在线，在线则转发消息，不在线则将消息存入数据库
def check_resendorinsert(message):
    global list_onlines
    global ls_all_messages
    recer = message[1]
    if recer in list_onlines:
        # 如果对方在线，暂存信息到列表中，找机会发送给对应客户端,并存入mysql数据库
        print("check函数的message:")
        print(message)
        ls_all_messages.append(list(message))
        add_one_message(list(message))
    else:
        # 写入数据库，包括发送，接受，内容
        # 暂时写不写入数据库，后续一定加入
        print(message)
        print("对方不在线{},数据存入mysql数据库".format(message))
        add_one_message(message)


def handle_messages(message):
    global list_onlines
    global ls_all_messages
    # print(message)
    try:
        message = eval(message)
    except:
        # 无视某个bug
        return 0
    if message[1] == "root" and message[2] == "在线":
        if message[0] in list_onlines:
            pass
            # print("{}上线了".format(message[0]))
        else:
            list_onlines.append(message[0])
            print("当前在线人：{}".format(str(list_onlines)))
        # 数字1message信息为状态确认函数
        return message[0]
    elif message[1] == "root" and message[2] == "退出":
        return 999
    elif message[1] == "tulingrobot":
        print("进入聊天")
        msg = chat(message[2])
        mess = ["tulingrobot", message[0], msg]
        check_resendorinsert(mess)
        print("handle函数的mess:")
        print(mess)
        # ls_all_messages.append(mess)
        return mess[1]
    else:
        check_resendorinsert(message)
        # 数字0表示message信息为用户发送的数据块
        return 0


class ChatServer(socketserver.BaseRequestHandler):
    # 处理用户发来的请求
    def handle(self):
        global ls_all_messages
        try:
            while True:
                data = self.request.recv(1024).decode("utf-8")
                # 逻辑层，用来处理用户请求
                int_sig = handle_messages(data)
                # 判断是否需要转发信息
                if int_sig == 0:
                    # 不考虑发送的问题
                    pass
                if int_sig == 999:
                    return 999
                else:
                    ls = ls_all_messages[:]
                    for i in ls:
                        if i[1] == int_sig:
                            self.request.sendall(str(i).encode("utf-8"))
                            print(ls_all_messages)
                            ls_all_messages.remove(i)
                            print("转发成功并删除数据")
        except:
            print("断开连接,剔除TCP客户端")
        finally:
            self.request.close()
            # 不关闭哈哈哈 找不到bug
            # self.server.server_close()

    def setup(self):
        print("开始连接", self.client_address)

    def finish(self):
        print("关闭链接",self.client_address)


def main():
    # 表示在线状态
    global list_onlines
    global ls_all_messages
    ls_all_messages = []
    print("TCP聊天服务器启动")
    list_onlines = []
    ip_port = ("127.0.0.1", 7890)
    # server = socketserver.TCPServer(ip_port, ChatServer)
    server = socketserver.ThreadingTCPServer(ip_port, ChatServer)
    server.serve_forever()
    print("123425364756879")


if __name__ == '__main__':
    main()



